package routers

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"seawolf-admin-go/utility/response"
	"seawolf-admin-go/utility/token"
	"seawolf-admin-go/utility/tools"
)

// MiddlewareHandlerIsLogin 登录中间件
func MiddlewareHandlerIsLogin(r *ghttp.Request) {
	// 不需要登录的URL
	if tools.RegexpContains(tools.GetAdminNoLoginUrl(), r.Request.URL.Path) {
		r.Middleware.Next()
		return
	}
	ctx := r.GetCtx()
	adminId, err := token.VerifyLoginToken(ctx, r.Header.Get("token"))
	if err != nil {
		r.Response.ClearBuffer()
		g.Log().Warning(ctx, "token错误："+err.Error())
		response.JsonExit(r, 10003, "请登录后继续操作")
		return
	}
	if adminId < 1 {
		r.Response.ClearBuffer()
		response.JsonExit(r, 10003, "请登录后继续操作")
		return
	}
	tools.SetAdminIdByRequest(r, adminId)
	// 继续执行后续的中间件和处理函数
	r.Middleware.Next()
}
